package com.zelin.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.Test;

import java.util.Date;

public class JWTAdviceDemo {
    //1. 创建jwt的token，此时带有过期时间
    @Test
    public void test01(){
        //1.定义过期时间
        long l = System.currentTimeMillis();
        Date date = new Date(1 + 60*1000);  //设置过期时间为1分钟
        //2. 定义jwtbuilder生成器对象
        JwtBuilder jwtBuilder =
                Jwts.builder().setId("2222")
                .setSubject("user")
                .setIssuedAt(new Date())
                .setExpiration(date)
                .signWith(SignatureAlgorithm.HS256,"zelin");
        //3. 创建token对象
        String token = jwtBuilder.compact();
        System.out.println("token:" + token);
    }
    //2。解析带有过期时间的token'
    @Test
    public void test(){
        //1. 得到要解析的token对象
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIyMjIyIiwic3ViIjoidXNlciIsImlhdCI6MTU4NTkxNzM0MywiZXhwIjo2MH0.XQeT5XgBF_nREHCPxqVASo3DN-tMmRm_usJiyvmvGz8";
        //2.生成claims对象
        Claims claims = Jwts.parser().setSigningKey("zelin").parseClaimsJws(token).getBody();
        //3. 生成解析结果
        String id = claims.getId();
        Date issuedAt = claims.getIssuedAt();
        String subject = claims.getSubject();
        Date expiration = claims.getExpiration();
        System.out.println( "id :" + id);
        System.out.println( "issuedAt :" + issuedAt);
        System.out.println( "subject :" + subject);
        System.out.println( "expiration :" + expiration);

    }
    //3.定义携带数据的claims
    @Test
    public void test03(){
        //3.1 定义jwtbuilder生成器
        JwtBuilder jwtBuilder = Jwts.builder().setId("3333")
                .setSubject("ttt")
                .setIssuedAt(new Date())
                .claim("roles","admin")
                .signWith(SignatureAlgorithm.HS256,"zelin");
        //3.2 创建token对象
        String token = jwtBuilder.compact();
        System.out.println(
                "token:"  + token
        );
    }
  //4. 解析携带的数据
    @Test
    public void test04(){
        //4.1 得到要解析的token
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIzMzMzIiwic3ViIjoidHR0IiwiaWF0IjoxNTg1OTE3ODYxLCJyb2xlcyI6ImFkbWluIn0.Wa-NRoJNNWwu6xUZHA-zfAxv9W9jnCWUEwOjFukkiE4";
        //4.2 解析token
        Claims claims = Jwts.parser().setSigningKey("zelin").parseClaimsJws(token).getBody();
        //4.3 得到数据
        String id = claims.getId();
        Date issuedAt = claims.getIssuedAt();
        String subject = claims.getSubject();
        Object roles = claims.get("roles");
        System.out.println("id:" + id);
        System.out.println("issuedAt:" + issuedAt);
        System.out.println("subject:" + subject);
        System.out.println("roles:" + roles);
    }
}
